'use client';

import Link from 'next/link';
import { type MouseEvent, type ReactNode, useContext } from 'react';
import classNames from 'classnames';
import { useRouter, useSelectedLayoutSegment } from 'next/navigation';
import { PostEditContext } from '@/contexts/post-edit';

export type TEditNavItemTranslatedField = 'name';

export default function EditNavItem({
  id,
  translatedFields = {
    name: 'name',
  },
  href = '',
  name,
  isShowName = true,
  iconName,
  isDisabled = false,
  isCustom = false,
  children,
  segment,
}: {
  id?: string;
  translatedFields?: Record<TEditNavItemTranslatedField, any>;
  href?: string;
  name: string;
  isShowName?: boolean;
  iconName?: string;
  isDisabled?: boolean;
  isCustom?: boolean;
  children?: ReactNode;
  segment?: any;
}) {
  const { config, onConfig } = useContext(PostEditContext);
  const router = useRouter();
  const selectedLayoutSegment = useSelectedLayoutSegment();
  const isActive =
    (segment === 'more' &&
      (selectedLayoutSegment === 'select-content' ||
        selectedLayoutSegment === 'content-type' ||
        selectedLayoutSegment === 'access-setting' ||
        selectedLayoutSegment === 'overview' ||
        selectedLayoutSegment === 'custom-tags' ||
        selectedLayoutSegment === 'statement' ||
        selectedLayoutSegment === 'cover' ||
        selectedLayoutSegment === 'chapter')) ||
    selectedLayoutSegment === segment;

  function onClick(e: MouseEvent<HTMLAnchorElement>) {
    if (!href) {
      e.stopPropagation();
      e.preventDefault();
    }

    if (isCustom && name === '居中') {
      onClickCenter();
    }

    if (isCustom && name === '返回') {
      router.push(`/posts/${id}`);
    }
  }

  function onClickCenter() {
    onConfig({
      isCenter: !config.isCenter,
    });
  }

  return (
    <li
      className={classNames('nav-item', {
        dropdown: !!children,
      })}
    >
      <Link
        href={href}
        onClick={onClick}
        data-bs-toggle={children ? 'dropdown' : ''}
        role="button"
        className={classNames('nav-link', {
          active: isActive,
          'dropdown-toggle': !!children,
          disabled: isDisabled,
        })}
        aria-current={isActive ? 'page' : 'false'}
      >
        {iconName && (
          <i
            className={classNames(
              'bi',
              {
                'me-2': isShowName,
              },
              iconName,
            )}
          ></i>
        )}
        {isShowName && translatedFields.name}
      </Link>
      {children && <ul className="dropdown-menu">{children}</ul>}
    </li>
  );
}
